package benny.ApkposStore.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.util.Log;

public class FileUtils {
	private String SDCardRoot;
	private String DataRoot;
	private String tag = "FileUtils";

	public FileUtils() {
		//得到当前外部存储设备的目录
		SDCardRoot = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator;
		DataRoot =Environment.getDataDirectory() + "/data/benny.ApkposStore/";
	}

	/**
	 * 在SD卡上创建文件
	 * 
	 * @throws IOException
	 */
	public File createFileInSDCard(String fileName, String dir)
			throws IOException {
		File file = new File(SDCardRoot + dir + File.separator + fileName);
		System.out.println("file---->" + file);
		
		if(!file.exists()) {
			file.createNewFile();
		}
		return file;
	}
	/**
	 * 在apk目录上创建文件
	 * 
	 * @throws IOException
	 */
	public File createFileInapk(String fileName, String dir)
			throws IOException {
		File file = new File(DataRoot + dir + File.separator + fileName);
		System.out.println("file---->" + file);
		
		if(!file.exists()) {
			file.createNewFile();
		}
		return file;
	}

	/**
	 * 在SD卡上创建目录
	 * 
	 * @param dirName
	 */
	public File creatSDDir(String dir) {
		File dirFile = new File(SDCardRoot + dir + File.separator);
		System.out.println(dirFile.mkdirs());
		return dirFile;
	}
	public File creatAPKDir(String dir) {
		File dirFile = new File(DataRoot + dir + File.separator);
		System.out.println(dirFile.mkdirs());
		return dirFile;
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public boolean isFileExist(String fileName, String path) {
		File file = new File(SDCardRoot + path + File.separator + fileName);
		return file.exists();
	}
	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public boolean isapkFileExist(String fileName, String path) {
		File file = new File(DataRoot + path + File.separator + fileName);
		return file.exists();
	}
	
	
	public interface WritingProgress {
		public void onProgress(int already);
	}
	
	/**
	 * 从输入流读取数据写到sd卡，带进度反馈，并且原子操作，如果写失败，则原来文件不会变化
	 * @param path 文件路径
	 * @param fileName 文件名
	 * @param input 输入流
	 * @return
	 */
	public boolean atomWrite2SDFromInput(String path, String fileName,
			InputStream input, WritingProgress progress) {

		File downloadingFile = null;
		File formalFile = null;
		OutputStream output = null;
		boolean res = false;
		try {
			//creatSDDir(path);
			creatAPKDir(path);			
			//step 1, 下载到正在下载中的临时文件
			String downloadingFileName = fileName + ".downloading";
			downloadingFile = createFileInapk(downloadingFileName, path);
			output = new FileOutputStream(downloadingFile);
			byte buffer[] = new byte[4 * 1024];
			int temp;
			int already = 0;
			while ((temp = input.read(buffer)) != -1) {
				output.write(buffer, 0, temp);
				already += temp;
				if(progress != null) {
					progress.onProgress(already);
				}
			}
			
			output.flush();
						
			//step 2, 重命名到正式文件
			synchronized(this) {

					formalFile = createFileInapk(fileName, path);
				
				if(downloadingFile.renameTo(formalFile) == false) {
					Log.e(tag, "atomWrite2SDFromInput: renameTo " + fileName + " failed");
				}
			}

			res = true;
		} 
		catch (Exception e) {
			Log.e(tag, "atomWrite2SDFromInput:" + e.getMessage());
			
		} 
		finally {
			if(downloadingFile != null) {
				downloadingFile.delete();
			}
			
//			if(formalFile != null) {
//				formalFile.delete();
//			}
			
			try {	
				if(output != null) {
					output.close();
				}				
			} 
			catch (Exception e) {
				Log.e(tag, "atomWrite2SDFromInput:" + e.getMessage());
			}
		}
		
		return res;
	}
	
	
	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 */
	public boolean write2SDFromInput(String path, String fileName,
			InputStream input) {

		return atomWrite2SDFromInput(path, fileName, input, null);
	}	

	public BitmapDrawable[] getimgFiles(String path) {
		BitmapDrawable[] drawables = null;
		File file = new File(SDCardRoot + File.separator + path);
		try {
			if (!file.exists()) {
				file.mkdir();
			} else {
				File[] files = file.listFiles();

				if (files != null && files.length > 0) {

					drawables = new BitmapDrawable[files.length];
					for (int i = 0; i <= files.length - 1; i++) {
						String PhtotPath = files[i].getPath();
						Bitmap bitmap = BitmapFactory.decodeFile(PhtotPath);
						drawables[i] = new BitmapDrawable(bitmap);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return drawables;
	}
	
	public String[] getimgFilespath(String path) {
		String[] Filespath = null;
		File file = new File(SDCardRoot + File.separator + path);
		try {
			if (!file.exists()) {
				file.mkdir();
			} else {
				File[] files = file.listFiles();
				
				if (files != null && files.length > 0) {
					
					Filespath = new String[files.length];
					for (int i = 0; i <= files.length - 1; i++) {
						String PhtotPath = files[i].getPath();
					//	Bitmap bitmap = BitmapFactory.decodeFile(PhtotPath);
						Filespath[i] = PhtotPath;
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return Filespath;
	}

}